'use strict';
const vkPay = require("vk-uni-pay");
module.exports = {
	/**
	 * XXXnameXXX
	 * @url admin/pages/kh/yhsj/czjl/refund 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */

	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			out_trade_no,
			refund_desc,
			refund_fee,
			_add_time,
			_add_time_str
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------

		if (userInfo.username != "admin") {
			res = {
				code: 0,
				msg: '操作失败！非admin账户不能操作退款'
			};
			return res;
		}

		// 这里不需要传pid的值，猜测可能是因为vkpay在发起支付时已记录该订单的pid值，发起退款时自动获取pid
		let refundRes = await vkPay.refund({
			out_trade_no: out_trade_no,
			refund_desc: refund_desc || "退款说明",
			refund_fee: refund_fee
		});
		if (refundRes.code !== 0) {
			return refundRes;
		}

		//获取订单信息
		let orderinfo = await db.collection('a_recharge').where({
			out_trade_no: out_trade_no
		}).get()
		//单独提取本次订单的金豆数量
		let bean_number = orderinfo.data[0].bean;
		//给用户账户减金豆
		let newInfo = await vk.baseDao.updateAndReturn({
			dbName: "uni-id-users",
			whereJson: {
				_id: orderinfo.data[0].user_id
			},
			dataJson: {
				balance: _.inc(-bean_number)
			}
		});
		//添加金豆收支明细
		let add_jindou = await vk.baseDao.add({
			dbName: "a_jindou_detail",
			dataJson: {
				user_id: orderinfo.data[0].user_id,
				nickname: orderinfo.data[0].nickname || "未绑定",
				change_num: bean_number, //变化的金豆数量
				changed_num: newInfo.balance, //支付后金豆余额
				change_reason: "退款扣除" + bean_number + "金豆",
				type: "expend", //类型：expend:支出,income:收入。
				appid: newInfo.appid || "",
				appname: newInfo.appname || "",
				os_name: orderinfo.data[0].os_name,
				_add_time,
				_add_time_str
			}
		});


		//修改订单状态为已退款。0：未支付  1：已支付  2：已退款
		let edit_pay_status = await db.collection('a_recharge').where({
			out_trade_no: out_trade_no
		}).update({
			pay_status: 2,
			remark: "已退款。退款金额(单位：分)：" + refund_fee || "全额"
		})

		// 执行add命令，添加退款操作日志
		let dbName = "a_log"; // 表名
		res.id = await vk.baseDao.add({
			dbName,
			dataJson: {
				user_id: userInfo._id,
				username: userInfo.username,
				ip: originalParam.context.CLIENTIP,
				osName: originalParam.context.osName,
				osVersion: originalParam.context.osVersion,
				deviceId: originalParam.context.deviceId,
				ua: originalParam.context.ua,
				remark: "后台操作退款记录",
				_add_time,
				_add_time_str
			}
		});

		res = {
			code: 0,
			msg: '退款成功'
		};

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}